package mybatis;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class MyBatisDemo {

    private static SqlSessionFactory sqlSessionFactory = null;

    static {
        try {
            InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {
//        List<Integer> ids = new ArrayList<>();
//        ids.add(1);
//        ids.add(2);
//        selectNameListByIds(ids);


//        List<User> users = new ArrayList<>();
//        users.add(new User(20,"Jack"));
//        users.add(new User(30,"Tom"));
//        int insertNum = insertList(users);
//        System.out.println(insertNum);

        System.out.println(selectNameById(1));

    }



    private static String selectNameById(Integer id){
        String name = null;
        try (SqlSession session = openSession()) {
            UserMapper mapper = session.getMapper(UserMapper.class);
            name = mapper.selectNameById(id);
        }
        return name;
    }

    private static List<String> selectNameListByIds(List<Integer> ids){
        List<String> names = null;
        try (SqlSession session = openSession()) {
            UserMapper mapper = session.getMapper(UserMapper.class);
            names = mapper.selectNameListByIds(ids);
        }
        return names;
    }

    private static Integer insertList(List<User> users){
        Integer res = null;
        try (SqlSession session = openSession()) {
            UserMapper mapper = session.getMapper(UserMapper.class);
            res = mapper.insertList(users);
        }
        return res;
    }



    private static SqlSession openSession(){
        //事务自动提交
        return sqlSessionFactory.openSession(true);
    }
}
